package com.hxd.otc.module.fiat_deal.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseMvpDialogFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.BankType;
import com.hxd.otc.common.enums.CardLevelEnum;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.PaymentMethodPopupWindow;
import com.hxd.otc.module.fiat_deal.bean.DealRequestBean;
import com.hxd.otc.module.fiat_deal.bean.DealResultDataBean;
import com.hxd.otc.module.fiat_deal.contract.DealDialogContract;
import com.hxd.otc.module.fiat_deal.presenter.DealDialogPresenter;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.my.bean.BankCardBean;
import com.hxd.otc.other.CustomBounceTopEnter;
import com.hxd.otc.other.SlideTopExit;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.LimitNumberTextWatcher;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * Created by lzy on 2018/11/21 0021.
 * description ${交易对话框Fragment}
 */
public class DealDialogFragment extends BaseMvpDialogFragment<DealDialogPresenter> implements DealDialogContract.IView {

    @BindView(R.id.iv_top)
    ImageView mIvTop;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.iv_close)
    ImageView mIvClose;
    @BindView(R.id.tv_error_message)
    TextView mTvErrorMessage;
    @BindView(R.id.et_virtual_count)
    EditText mEtVirtualCount;//数量
    @BindView(R.id.tv_virtual_type)
    TextView mTvVirtualType;
    @BindView(R.id.iv_clear_virtual)
    ImageView mIvClearVirtual;
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R.id.tv_sure)
    TextView mTvSure;
    @NonNull
    @BindView(R.id.tv_payment_method)
    TextView mTvPaymentMethod;
    @BindView(R.id.tv_quota)
    TextView mTvQuota;
    @BindView(R.id.et_money)
    EditText mEtMoney;//金额
    @BindView(R.id.tv_money_unit)
    TextView mTvMoneyUnit;
    @BindView(R.id.iv_clear_money)
    ImageView mIvClearMoney;
    @BindView(R.id.tv_ask_payment_method)
    TextView mTvAskPaymentMethod;

    public static final String EXTRA_DEAL_DADA = "deal_dada";
    public static final String EXTRA_DEAL_TYPE = "deal_type";
    public static final String EXTRA_TRANSACTION_PAIR = "transaction_pair";
    private LimitNumberTextWatcher mVirtualWatcher;
    private LimitNumberTextWatcher mMoneyWatcher;


    private DealRequestBean mRequestDealBean;
    private OnConfirmListener mOnConfirmListener;
    private Disposable mDisposable;
    private BigDecimal mSinglePriceBigDecimal;
    private BigDecimal mRealMaxVolumeDecimal;
    String bankCardRealName;

    MultipleBlocksDialog bindBankCardDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_fragment_deal;
    }

    @Override
    protected DealDialogPresenter createPresenter() {
        return new DealDialogPresenter(this);
    }

    @Override
    protected void initBundle(Bundle arguments) {
        mPresenter.setDealData((DealResultDataBean.Data) arguments.getSerializable(EXTRA_DEAL_DADA));
        mPresenter.setDealType(arguments.getInt(EXTRA_DEAL_TYPE));
        mPresenter.setTransactionPair(arguments.getString(EXTRA_TRANSACTION_PAIR));
    }

    @Override
    protected void initView() {
        String[] split = mPresenter.getTransactionPair().split("/");
        DealResultDataBean.Data dealData = mPresenter.getDealData();
        boolean isBuy = mPresenter.getDealType() == Constant.Deal.TYPE_BUY;

        //限额
        mTvQuota.setText(ResourceUtil.getString(R.string.deal_dialog_quota, StringUtil.handleZero(String.valueOf(dealData.minMoney)), StringUtil.handleZero(String.valueOf(dealData.maxMoney)), dealData.supportCurrencyCode));

        //交易方的收款方式
        String supportPay = StringUtil.emptyIfNull(dealData.supportPay);
        StringBuilder sb = new StringBuilder();
        for (BankType bankType : BankType.values()) {
            if (supportPay.contains(bankType.getTypeStr())) {
                sb.append(bankType.getBankName()).append(" ");
            }
        }
        mTvAskPaymentMethod.setText(sb.toString());
        mTvPaymentMethod.setVisibility(View.VISIBLE);

        mSinglePriceBigDecimal = new BigDecimal(dealData.price);

        //设置单位符号
        if (split.length > 0) {
            mTvVirtualType.setText(split[0]);
            mTvPrice.setText(String.format(ResourceUtil.getString(R.string.deal_dialog_unit_price)
                    , mSinglePriceBigDecimal.setScale(2, RoundingMode.DOWN).toString(), split[1]));
            mTvMoneyUnit.setText(split[1]);
        }

        //设置标题
        mTvTitle.setText(ResourceUtil.getString(isBuy ? R.string.buy_aec : R.string.sale_aec, dealData.symbol));

        //设置虚拟币输入框提示文案
        BigDecimal volumeDecimal = new BigDecimal(dealData.volume);
        BigDecimal lockVolumeDecimal = new BigDecimal(dealData.lockVolume);
        BigDecimal successVolumeDecimal = new BigDecimal(dealData.successVolume);

        mRealMaxVolumeDecimal = volumeDecimal.subtract(lockVolumeDecimal).subtract(successVolumeDecimal).setScale(8, RoundingMode.DOWN);

        BigDecimal maxMoneyDecimal = new BigDecimal(dealData.maxMoney);

        BigDecimal maxQuotaBigDecimal = maxMoneyDecimal.divide(mSinglePriceBigDecimal, 8, RoundingMode.HALF_DOWN);
        if (mRealMaxVolumeDecimal.doubleValue() > maxQuotaBigDecimal.doubleValue()) {
            mRealMaxVolumeDecimal = maxQuotaBigDecimal;
        }
        mEtVirtualCount.setHint(ResourceUtil.getString(isBuy ? R.string.max_buy : R.string.max_sell, mRealMaxVolumeDecimal.toString()));

        //设置输入金额对话框的提示文案
        mEtMoney.setHint(ResourceUtil.getString(isBuy ? R.string.max_buy : R.string.max_sell, mRealMaxVolumeDecimal.multiply(mSinglePriceBigDecimal).setScale(2, RoundingMode.DOWN).toString()));

        if (isBuy) {
            String[] supportPays = mPresenter.getDealData().supportPay.split(",");
            if (supportPays.length == 1) {
                BankCardBean bean = new BankCardBean();
                bean.setType(Integer.parseInt(supportPays[0]));
                if (supportPays[0].equals("3")) {
                    bean.setBankName(getString(R.string.bank_card));
                }
                updateSelBankCard(bean);
            }
        }

    }

    @Override
    protected void initEvent() {
        //虚拟币输入监听
        mVirtualWatcher = new LimitNumberTextWatcher(mEtVirtualCount, 9, 8) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //移除金额和数量输入框监听
                mEtVirtualCount.removeTextChangedListener(mVirtualWatcher);
                mEtMoney.removeTextChangedListener(mMoneyWatcher);
                //进行位数限制
                super.onTextChanged(s, start, before, count);
                //重新获取位数限制后的数据
                String virtualStr = mEtVirtualCount.getText().toString().trim();
                //更新错误提示
                updateErrorMessageView(virtualStr);
                //更新金额输入框
                if (TextUtils.isEmpty(virtualStr)) {
                    mEtMoney.setText("");
                } else {
                    BigDecimal virtualDecimal = new BigDecimal(virtualStr);
                    BigDecimal totalMoneyDecimal = virtualDecimal.multiply(mSinglePriceBigDecimal).setScale(2, RoundingMode.DOWN);
                    mEtMoney.setText(totalMoneyDecimal.toString());
                }
                //更新清除按钮状态
                updateClearStatus();


                //重新添加监听
                mEtVirtualCount.addTextChangedListener(mVirtualWatcher);
                mEtMoney.addTextChangedListener(mMoneyWatcher);
            }
        };

        mMoneyWatcher = new LimitNumberTextWatcher(mEtMoney, 9, 2) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //移除金额和数量输入框监听
                mEtVirtualCount.removeTextChangedListener(mVirtualWatcher);
                mEtMoney.removeTextChangedListener(mMoneyWatcher);
                //进行位数限制
                super.onTextChanged(s, start, before, count);
                //重新获取位数限制后的数据
                String moneyStr = mEtMoney.getText().toString().trim();
                if (TextUtils.isEmpty(moneyStr)) {
                    mEtVirtualCount.setText(""); //更新数量
                    updateErrorMessageView(""); //更新错误提示
                } else {
                    BigDecimal newVirtualNumsBigDecimal = new BigDecimal(moneyStr).divide(mSinglePriceBigDecimal, 8, RoundingMode.DOWN);
                    mEtVirtualCount.setText(newVirtualNumsBigDecimal.toString());//更新数量
                    updateErrorMessageView(newVirtualNumsBigDecimal.toString());//更新错误提示
                }
                //更新清除按钮状态
                updateClearStatus();
                //重新添加监听
                mEtVirtualCount.addTextChangedListener(mVirtualWatcher);
                mEtMoney.addTextChangedListener(mMoneyWatcher);
            }
        };

        mEtMoney.addTextChangedListener(mMoneyWatcher);
        mEtVirtualCount.addTextChangedListener(mVirtualWatcher);
    }

    private void updateClearStatus() {
        mIvClearVirtual.setVisibility(!TextUtils.isEmpty(mEtVirtualCount.getText()) && TextUtils.getTrimmedLength(mEtVirtualCount.getText()) > 0 ?
                View.VISIBLE : View.GONE);
        mIvClearMoney.setVisibility(!TextUtils.isEmpty(mEtMoney.getText()) && TextUtils.getTrimmedLength(mEtMoney.getText()) > 0 ?
                View.VISIBLE : View.GONE);
    }

    private void updateErrorMessageView(String virtualStr) {
        if (DataUtils.isEmpty(virtualStr)) {
            mTvErrorMessage.setText("");
        } else {
            BigDecimal virtualDecimal = new BigDecimal(virtualStr);
            double curTotalMoney = virtualDecimal.multiply(mSinglePriceBigDecimal).setScale(2, RoundingMode.DOWN).doubleValue();

            if (virtualDecimal.doubleValue() > mRealMaxVolumeDecimal.doubleValue()) {
                mTvErrorMessage.setText(R.string.the_amount_you_enter_is_greater_than_the_maximum_limit);
            } else if (curTotalMoney < mPresenter.getDealData().minMoney) {//小于最小限额
                mTvErrorMessage.setText(R.string.the_amount_you_enter_is_lesser_than_the_minimum_limit);
            } else {
                mTvErrorMessage.setText("");
            }
        }
    }

    @Override
    protected void onDialogAnim(Window window) {
        window.getAttributes().windowAnimations = R.style.dealDialogAnim;
    }

    @Override
    protected void initData() {
        //当卖出时，请求自己的收款方式
        if (mPresenter.getDealType() == Constant.Deal.TYPE_SELL) {
            mPresenter.getUserBankCard();
        }

        //开启倒计时
        startCountdown();
    }

    private void startCountdown() {
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (mTvCancel != null) {
                            mTvCancel.setText(ResourceUtil.getString(R.string.cancel_millis, 60 - aLong));
                        }
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        UIUtils.dismissDialogFragment(DealDialogFragment.this);
                    }
                })
                .subscribe();
    }

    @OnClick({R.id.iv_close, R.id.tv_cancel, R.id.tv_sure, R.id.iv_clear_virtual, R.id.tv_payment_method, R.id.iv_clear_money})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_sure:
                onSure();
                break;
            case R.id.iv_clear_virtual:
                mEtVirtualCount.setText("");
                break;
            case R.id.tv_payment_method:
                onSelectPaymentMethod();
                break;
            case R.id.iv_clear_money:
                mEtMoney.setText("");
                break;
        }
    }

    private PaymentMethodPopupWindow mPaymentMethodPopupWindow;

    private void onSelectPaymentMethod() {

        if (mPresenter.getDealType() == Constant.Deal.TYPE_BUY) {
            String[] supportPay = mPresenter.getDealData().supportPay.split(",");
            if (supportPay.length <= 0) {
                return;
            }
            ArrayList<BankCardBean> bankCardList = new ArrayList<>();
            for (int i = 0; i < supportPay.length; i++) {
                BankCardBean bean = new BankCardBean();
                bean.setType(Integer.parseInt(supportPay[i]));
                if (supportPay[i].equals("3")) {
                    bean.setBankName(getString(R.string.bank_card));
                }
                bankCardList.add(bean);
            }

            if (mPaymentMethodPopupWindow == null) {
                mPaymentMethodPopupWindow = new PaymentMethodPopupWindow(getContext());
                mPaymentMethodPopupWindow.offset(0, 0)
                        .setOnSelPayMethodListener(new PaymentMethodPopupWindow.OnSelPayMethodListener() {
                            @Override
                            public void onSelPayMethod(BankCardBean bankCardBean) {
                                updateSelBankCard(bankCardBean);
                            }
                        })
                        .setWidth(mTvPaymentMethod.getWidth())
                        .gravity(Gravity.BOTTOM)
                        .showAnim(new CustomBounceTopEnter())
                        .dismissAnim(new SlideTopExit())
                        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                if (mTvPaymentMethod != null) {
                                    mTvPaymentMethod.setSelected(false);
                                }
                            }
                        });
            }
            mPaymentMethodPopupWindow
                    .anchorView(mTvPaymentMethod)
                    .setSelItem(mPresenter.getSelBankCardBean())
                    .setData(bankCardList);
            mPaymentMethodPopupWindow.show();
            mTvPaymentMethod.setSelected(true);

        } else {
            ArrayList<BankCardBean> bankCardList = mPresenter.getBankCardList();
            if (bankCardList == null) return;

            if (mPaymentMethodPopupWindow == null) {
                mPaymentMethodPopupWindow = new PaymentMethodPopupWindow(getContext());
                mPaymentMethodPopupWindow.offset(0, 0)
                        .setOnSelPayMethodListener(new PaymentMethodPopupWindow.OnSelPayMethodListener() {
                            @Override
                            public void onSelPayMethod(BankCardBean bankCardBean) {
                                updateSelBankCard(bankCardBean);
                            }
                        })
                        .setWidth(mTvPaymentMethod.getWidth())
                        .gravity(Gravity.BOTTOM)
                        .showAnim(new CustomBounceTopEnter())
                        .dismissAnim(new SlideTopExit())
                        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                if (mTvPaymentMethod != null) {
                                    mTvPaymentMethod.setSelected(false);
                                }
                            }
                        });
            }
            mPaymentMethodPopupWindow
                    .anchorView(mTvPaymentMethod)
                    .setSelItem(mPresenter.getSelBankCardBean())
                    .setData(bankCardList);
            mPaymentMethodPopupWindow.show();
            mTvPaymentMethod.setSelected(true);
        }

    }

    @Override
    public void updateSelBankCard(BankCardBean bankCardBean) {
        mPresenter.setSelBankCard(bankCardBean);
        BankType bankType = BankType.getBankTypeByValue(bankCardBean.getType());
        mTvPaymentMethod.setCompoundDrawablesWithIntrinsicBounds(ResourceUtil.getDrawable(bankType.getSelectPaymentMethodLogo()),
                null, ResourceUtil.getDrawable(R.drawable.selector_publish_advert_menu_arrow), null);
        switch (bankCardBean.getType()) {//1微信2支付宝3银行卡
            case 1:
                mTvPaymentMethod.setText(R.string.weixin);
                break;
            case 2:
                mTvPaymentMethod.setText(R.string.alipay);
                break;
            case 3:
            default:
                mTvPaymentMethod.setText(StringUtil.emptyIfNull(bankCardBean.getBankName()));
                bankCardRealName = bankCardBean.getRealName();
                break;
        }
    }


    @Override
    public void dismiss() {
        setOnConfirmListener(null);
        super.dismiss();
    }

    @Override
    public void dismissAllowingStateLoss() {
        setOnConfirmListener(null);
        super.dismissAllowingStateLoss();
    }

    @Override
    public void onDestroy() {
        UIUtils.dismissDialog(mPaymentMethodPopupWindow);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        super.onDestroy();
    }

    /**
     * 确认
     */
    private void onSure() {
        String virtualStr = mEtVirtualCount.getText().toString().trim();
        if (TextUtils.isEmpty(virtualStr)) {
            BlocksToast.get().showToast(R.string.please_input_deal_number);
            return;
        }
        DealResultDataBean.Data dealData = mPresenter.getDealData();

        if (Double.valueOf(virtualStr) > mRealMaxVolumeDecimal.doubleValue()) {
            BlocksToast.get().showToast(R.string.deal_number_not_gt_wallet, mRealMaxVolumeDecimal.toString());
            return;
        }
        if (Double.valueOf(virtualStr) <= 0) {
            BlocksToast.get().showToast(R.string.deal_number_most_gt_zero, 0);
            return;
        }
        //用户输入的数量乘以单价得出的交易金额如果不在限额范围内，点击确定，提示“交易金额超出限额”。
        Double virtual = Double.valueOf(virtualStr);
        double curTotalMoney = DataUtils.mul(virtual, Double.valueOf(dealData.price), 2);

        if (virtual > mRealMaxVolumeDecimal.doubleValue()) {
            showToast(getString(R.string.the_amount_you_enter_is_greater_than_the_maximum_limit));
            return;
        }
        if (curTotalMoney < dealData.minMoney) {//小于最小限额
            showToast(getString(R.string.the_amount_you_enter_is_lesser_than_the_minimum_limit));
            return;
        }
        if (UserHelper.getCardLevel().equals(CardLevelEnum.LEVEL_0)) {
            if (bindBankCardDialog == null) {
                bindBankCardDialog = new MultipleBlocksDialog(getContext());
                bindBankCardDialog
                        .setContent(getString(R.string.only_real_name_auth_can_buy))
                        .setTitleGone()
                        .setTvSure(getString(R.string.go_to_real_name_auth), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                bindBankCardDialog.dismiss();
                                Intent intent = new Intent(getActivity(), SecurityCenterActivity.class);
                                startActivityForResult(intent, 123);
                            }
                        });
            }
            bindBankCardDialog.show();
            return;
        }

        String detailPay = null;

        //卖出时判断是否选择收款方式
        int dealType = mPresenter.getDealType();
        if (dealType == Constant.Deal.TYPE_SELL) {
            BankCardBean selBankCardBean = mPresenter.getSelBankCardBean();
            if (selBankCardBean == null) {
                showToast(getString(R.string.please_select_pay_mode));
                return;
            }
            if ((!UserHelper.isSilver() && !UserHelper.isMerchant()) && (selBankCardBean.getBankType() == BankType.BANK)) {
                if (!selBankCardBean.getRealName().equals(UserHelper.getRealName())) {
                    showToast(getString(R.string.real_name_and_name_not_complay_please_add_again));
                    return;
                }

            }
//            detailPay = selBankCardBean.getBankType() == BankType.BANK ? selBankCardBean.getId() : selBankCardBean.getBankType().getType() + "";
            detailPay = selBankCardBean.getId();

        } else if (dealType == Constant.Deal.TYPE_BUY) {
            BankCardBean selBankCardBean = mPresenter.getSelBankCardBean();
            if (selBankCardBean == null) {
                showToast(getString(R.string.please_select_pay_mode));
                return;
            }
            detailPay = selBankCardBean.getType() + "";
        }
        mRequestDealBean = new DealRequestBean();
        mRequestDealBean.dealType = dealType;
        mRequestDealBean.volume = virtualStr;
        mRequestDealBean.symbol = dealData.symbol;
        mRequestDealBean.orderId = dealData.id;
        mRequestDealBean.coinId = dealData.coinId;
        mRequestDealBean.detailPay = detailPay;
        mRequestDealBean.totalPrice = mEtMoney.getText().toString();

        if (mOnConfirmListener != null) {
            mOnConfirmListener.onConfirm(mRequestDealBean);
        }
    }

    public static DealDialogFragment getInstance(DealResultDataBean.Data dealData, int dealType, String transactionPair) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_DEAL_DADA, dealData);
        bundle.putInt(EXTRA_DEAL_TYPE, dealType);
        bundle.putString(EXTRA_TRANSACTION_PAIR, transactionPair);
        DealDialogFragment dealDialogFragment = new DealDialogFragment();
        dealDialogFragment.setArguments(bundle);
        return dealDialogFragment;
    }

    public void setDealDialogConfirmBtnEnable(boolean enable) {
        if (mTvSure != null) mTvSure.setEnabled(enable);
    }


    @Override
    public void getUserBankCardFail(String errMessage) {

    }

    public interface OnConfirmListener {
        void onConfirm(DealRequestBean bean);
    }

    public DealDialogFragment setOnConfirmListener(OnConfirmListener onConfirmListener) {
        mOnConfirmListener = onConfirmListener;
        return this;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            super.show(manager, tag);
        } catch (Exception ignore) {
        } catch (Error ignored) {
        }
    }
}
